/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.gp.patient.measurement;

import be.ugent.medirem.logic.MeasurementRemote;
import be.ugent.medirem.logic.MedicationRemote;
import be.ugent.medirem.persistence.entity.details.MeasurementTypeDetails;
import be.ugent.medirem.persistence.entity.details.UnitDetails;
import be.ugent.medirem.persistence.entity.values.MeasurementValues;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Simon
 */
public class AddPatientMeasurementServlet extends HttpServlet {

    @EJB
    private MedicationRemote medicationBean;
    @EJB
    private MeasurementRemote measurementBean;

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Long pid = (Long) request.getSession().getAttribute("pid");
        request.setAttribute("patientid", pid);

        List<UnitDetails> list = medicationBean.getAllUnits();
        List<MeasurementTypeDetails> types = measurementBean.getAllMeasurementTypes();

        request.setAttribute("units", list);
        request.setAttribute("types", types);

        request.getRequestDispatcher("/gp/patient/measurement/add.jsp").forward(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Long pid = (Long) request.getSession().getAttribute("pid");
        request.setAttribute("patientid", pid);

        MeasurementValues m = (MeasurementValues) request.getAttribute("measurement");
        m.setDateTaken(new Date());
        try {
            measurementBean.addMeasurement(pid, m);
        } catch (Exception ex) {
            request.getSession().setAttribute("flash", "An error occured when trying to add this measurement!");
        }

        response.sendRedirect(request.getContextPath() + "/gp/patient/measurements");
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
